package com.smap.control;

import java.util.ArrayList;
import java.util.List;

import com.smap.core.MapStatus;
import com.smap.core.XY;
import com.smap.event.MapEvent;

public class HistoryControl extends AbstractControl {

	List<MapStatus> history = new ArrayList<MapStatus>();
	int index = 0;

	MapStatus current;

	@Override
	void onEvent(MapEvent evt) {
		if (MapEvent.EVT_MAP_DRAWN.equals(evt.type)) {
			MapStatus status = (MapStatus) evt.data;
			if (!status.equals(current)) {
				// remove everything
				int length = history.size();
				for (int i = 0; i < (length - 1 - index); i++) {
					history.remove(index + 1);
				}
				if ((history.size() == 0)
						|| !status.equals(history.get(history.size() - 1))) {
					history.add(status);
				}
				index = history.size() - 1;
			}

			if (index >= (history.size() - 1)) {
				toolBar.disable("forward");
			} else {
				toolBar.enable("forward");
			}
			if (index <= 0) {
				toolBar.disable("back");
			} else {
				toolBar.enable("back");
			}
		}
	}

	public void go() {
		if (history.size() == 0) {
			return;
		}
		index = Math.min(index, history.size() - 1);
		index = Math.max(0, index);
		current = history.get(index);
		map.zoom(new XY(current.x, current.y), current.zoom);
	}

	@Override
	public void execute(String cmd) {
		if ("back".equals(cmd)) {
			index--;
			go();
		} else if ("forward".equals(cmd)) {
			index++;
			go();
		}
	}

	@Override
	public String[] getCmd() {
		return new String[] { "back", "forward" };
	}

	@Override
	void init() {

	}

}
